import http from './http';

// 查询容器列表（支持查询参数）
export const searchContainers = async (queryParams = {}) => {
  try {
    // todo 从本地存储获取认证 Token（如存在）
    // const token = typeof window !== 'undefined'
    //   ? (window.localStorage.getItem('auth_token') || '')
    //   : '';

    // 注意：后端类级映射为 /api/container，这里保持单数路径
    const response = await http.get(`/container`, {
      params: queryParams,
      // headers: token ? { Authorization: `Bearer ${token}` } : {},
    });
    return response.data; // 期望返回 { code, data, message }
  } catch (error) {
    throw new Error(error.response?.data?.message || '查询容器列表失败');
  }
};

// 创建容器
export const createContainer = async (containerData) => {
  try {
    const response = await http.post(`/containers`, containerData);
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '创建容器失败');
  }
};

// 创建容器并绑定计划
export const createContainerAndBindPlan = async (planId, containerData) => { 
  try {
    console.log('发送请求到:', `/plans/${planId}/containers`);
    console.log('请求数据:', containerData);
    
    const response = await http.post(`/plans/${planId}/containers`, containerData);
    
    console.log('响应状态:', response.status);
    console.log('响应数据:', response.data);
    
    return response.data;
  } catch (error) {
    console.error('API错误详情:', error);
    console.error('响应数据:', error.response?.data);
    throw new Error(error.response?.data?.message || '创建容器并绑定计划失败');
  }
};
//结束容器
export const endContainerApi = async (containerId) => {
  try {
    const response = await http.post(`/container/${containerId}/end`);
    return response.data;
  }
  catch (error) {
    throw new Error(error.response?.data?.message || '结束容器失败');
  }
};

// 上传容器结束证据图片（multipart/form-data）
export const uploadContainerEvidence = async (containerId, file) => {
  try {
    const formData = new FormData();
    formData.append('evidence', file);
    const response = await http.post(
      `/container/${containerId}/evidence`,
      formData,
      { headers: { 'Content-Type': 'multipart/form-data' } }
    );
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '上传结束证据失败');
  }
};
// 绑定容器到计划
export const bindContainerToPlan = async (planId, containerId) => {
  try {
    const response = await http.post(`/plans/${planId}/containers`, {
      containerId
    });
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '绑定容器失败');
  }
};